package com.jieshuibao.controller;

import java.text.NumberFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.mapper.BuyWishRequest;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.Wish;
import com.jieshuibao.model.db.WishExBuy;
import com.jieshuibao.model.db.WishExample;
import com.jieshuibao.model.db.Wishbuy;
import com.jieshuibao.model.db.WishbuyExample;
import com.jieshuibao.model.db.WishbuyExample.Criteria;
import com.jieshuibao.model.db.Wishcode;
import com.jieshuibao.model.db.WishcodeExample;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.MedalGetRequest;
import com.jieshuibao.model.domain.WishBuyRequest;
import com.jieshuibao.model.domain.WishBuyResponse;
import com.jieshuibao.model.domain.WishCodeRequest;
import com.jieshuibao.model.domain.WishCodeResponse;
import com.jieshuibao.model.domain.WishResponse;
import com.jieshuibao.model.domain.WxAppResponse;
import com.jieshuibao.service.PayVipBanlanceService;
import com.jieshuibao.service.RedisService;
import com.jieshuibao.service.UserService;
import com.jieshuibao.service.WeiXinPayService;
import com.jieshuibao.service.WishService;
import com.jieshuibao.service.WishbuyService;
import com.jieshuibao.service.WishcodeService;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;
@Controller
@RequestMapping(value="/wish")
public class WishController {
	
	private static final Logger logger = LoggerFactory
			.getLogger("WishController.class");

	private static final ObjectMapper mapper = new ObjectMapper();
	
	@Resource
	private RedisService redisService;
	
	@Resource
	private UserService userService;
	
	@Resource
	private WishService wishService;
	
	@Resource
	private WishbuyService wishbuyService;
	
	@Resource
	private WishcodeService wishcodeService;
	
	@Resource
	private PayVipBanlanceService payVipBanlanceService;
	
	@Resource
	private WeiXinPayService weiXinPayService;
	
	
	// 愿望列表
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public Object queryWishList(HttpServletRequest request) {
		WishResponse wishResponse = new WishResponse();
		try {
			
			String cookieId = request.getHeader("cookieId");
			logger.info("接收：" + mapper.writeValueAsString(cookieId));
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							WishExample wishExample = new WishExample();
							wishExample.setOrderByClause("orderNum");
							List<Wish> list = wishService.getWishsByExample(wishExample);
							if(list!=null){
								for (Wish wish : list) {
									String id = wish.getId();
									Integer buyCount = wishbuyService.getSumBuyCount(id);
									
									int totalPrice = wish.getTotalPrice();
									if(buyCount!=null){
										//NumberFormat numberFormat = NumberFormat.getInstance();  
									    //numberFormat.setMaximumFractionDigits(0);  
									    //String result = numberFormat.format((float) buyCount / (float) totalPrice * 100); 
									    //Integer schedule = Integer.valueOf(result); 
									    int c=buyCount*100/totalPrice;
									    double schedule=(double)c/100*100;
										int remain=totalPrice-buyCount;
										wish.setSchedule((int)schedule);
										if(remain<=0){
											wish.setRemain(0);	
											wish.setSchedule(100);
										}else {
											wish.setRemain(remain);
										}
									}else {
										wish.setRemain(totalPrice);
									}
								}
								String string = redisService.get("medal_code");
								if(string!=null){
									String replaceAll = string.replaceAll(",", "        ");
									wishResponse.setNotices(replaceAll);
								}else {
									wishResponse.setNotices("");
								}
								wishResponse.setNotices(PayTypeUtil.MARQUEE);
								wishResponse.setWishs(list);
								wishResponse.setCode("1");
							}
						} else {
							wishResponse.setCode("2");
							wishResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						wishResponse.setCode("2");
						wishResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					wishResponse.setCode("2");
					wishResponse.setDes("请重新登录");
				}

			} else {
				// 未登录
				wishResponse.setCode("2");
				wishResponse.setDes("请重新登录");
			}
			logger.info("返回："
					+ mapper.writeValueAsString(wishResponse));
		} catch (Exception e) {
			e.printStackTrace();
			wishResponse.setCode("0");
			wishResponse.setDes("系统繁忙请稍后再试！");
		}

		return wishResponse;
	}
	// 一个愿望
	@RequestMapping(value = "/one", method = RequestMethod.POST)
	@ResponseBody
	public Object queryWish(HttpServletRequest request,
			@RequestBody MedalGetRequest medalGetRequest) {
		WishResponse wishResponse = new WishResponse();
		try {
			
			String cookieId = request.getHeader("cookieId");
			logger.info("接收：" + mapper.writeValueAsString(medalGetRequest));
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String uuid = medalGetRequest.getUuid();
							Wish wishById = wishService.getWishById(uuid);
							if(wishById!=null){
								String id = wishById.getId();
								Integer buyCount = wishbuyService.getSumBuyCount(id);
								
								int totalPrice = wishById.getTotalPrice();
								if(buyCount!=null){
									NumberFormat numberFormat = NumberFormat.getInstance();  
								    numberFormat.setMaximumFractionDigits(0);  
								   // String result = numberFormat.format((float) buyCount / (float) totalPrice * 100); 
								    //Integer schedule = Integer.valueOf(result); 
								    int c=buyCount*100/totalPrice;
								    double schedule=(double)c/100*100;
									int remain=totalPrice-buyCount;
									wishById.setSchedule((int)schedule);
									if(remain<=0){
										wishById.setRemain(0);	
										wishById.setSchedule(100);
									}else {
										wishById.setRemain(remain);
									}
								}else {
									wishById.setRemain(totalPrice);
								}
								
								String string = redisService.get("medal_code");
								if(string!=null){
									String replaceAll = string.replaceAll(",", "        ");
									wishResponse.setNotices(replaceAll);
								}else {
									wishResponse.setNotices("");
								}
								wishResponse.setWish(wishById);
								wishResponse.setCode("1");
							}else {
								wishResponse.setCode("3");
								wishResponse.setDes("数据格式错误");
							}
						} else {
							wishResponse.setCode("2");
							wishResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						wishResponse.setCode("2");
						wishResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					wishResponse.setCode("2");
					wishResponse.setDes("请重新登录");
				}

			} else {
				// 未登录
				wishResponse.setCode("2");
				wishResponse.setDes("请重新登录");
			}
			logger.info("返回："
					+ mapper.writeValueAsString(wishResponse));
		} catch (Exception e) {
			e.printStackTrace();
			wishResponse.setCode("0");
			wishResponse.setDes("系统繁忙请稍后再试！");
		}

		return wishResponse;
	}
	// 愿望记录
	@RequestMapping(value = "/buyList", method = RequestMethod.POST)
	@ResponseBody
	public Object wishBuyList(HttpServletRequest request,
			@RequestBody WishBuyRequest wishBuyRequest) {
		WishBuyResponse wishBuyResponse = new WishBuyResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(wishBuyRequest));
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String uuid = wishBuyRequest.getUuid();
							int sinceId = wishBuyRequest.getSinceId();
							int maxId = wishBuyRequest.getMaxId();
							
							if (sinceId <= 0) {
								sinceId = 1;
							}
							if (maxId <= 0 || maxId < sinceId) {
								maxId = sinceId;
							}
							if(uuid!=null&&!uuid.equals("")){
								WishbuyExample wishbuyExample = new WishbuyExample();
								wishbuyExample.setOrderByClause("createDate desc");
								Criteria createCriteria = wishbuyExample.createCriteria();
								createCriteria.andWishIdEqualTo(uuid);
								createCriteria.andStatusEqualTo("0");
								wishbuyExample.setPageIndex(sinceId - 1);
								wishbuyExample.setPageSize(maxId - sinceId + 1);
								List<WishExBuy> list = wishbuyService.getWishBuyUserPage(wishbuyExample);
								if(list!=null){
									for (WishExBuy wishExBuy : list) {
										String phone = wishExBuy.getPhone();
										String replaceAll = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
										wishExBuy.setPhone(replaceAll);
									}
								}
								wishBuyResponse.setWishBuyUsers(list);
								wishBuyResponse.setCode("1");
								wishBuyResponse.setMaxId(sinceId+ list.size() - 1);
								wishBuyResponse.setSinceId(sinceId);
								wishBuyResponse.setRows(list.size());
								
							}else {
								wishBuyResponse.setCode("3");
								wishBuyResponse.setDes("数据格式错误");
							}
						} else {
							
							wishBuyResponse.setCode("2");
							wishBuyResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						wishBuyResponse.setCode("2");
						wishBuyResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					wishBuyResponse.setCode("2");
					wishBuyResponse.setDes("请重新登录");
				}

			} else {
				// 未登录
				wishBuyResponse.setCode("2");
				wishBuyResponse.setDes("请重新登录");
			}
			logger.info("返回："
					+ mapper.writeValueAsString(wishBuyResponse));
		} catch (Exception e) {
			e.printStackTrace();
			wishBuyResponse.setCode("0");
			wishBuyResponse.setDes("系统繁忙请稍后再试！");
		}

		return wishBuyResponse;
	}
		//查看许愿号
	@RequestMapping(value = "/codeList", method = RequestMethod.POST)
	@ResponseBody
	public Object wishCodeList(HttpServletRequest request,
			@RequestBody WishCodeRequest wishCodeRequest) {
		WishCodeResponse wishCodeResponse = new WishCodeResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(wishCodeRequest));
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							String userId = wishCodeRequest.getUserId();
							String uuid = wishCodeRequest.getUuid();
							String wishType = wishCodeRequest.getWishType();
							
							if(userId!=null&&!userId.equals("")&&uuid!=null&&!uuid.equals("")&&wishType!=null&&!wishType.equals("")){
								WishcodeExample wishcodeExample = new WishcodeExample();
								wishcodeExample.setOrderByClause("code desc");
								com.jieshuibao.model.db.WishcodeExample.Criteria criteria = wishcodeExample.createCriteria();
								if(wishType.equals("single")){
									criteria.andBuywithIdEqualTo(uuid);
								}else {
									criteria.andWishIdEqualTo(uuid);
								}
								criteria.andUserIdEqualTo(userId);
								List<Wishcode> list = wishcodeService.getWishcodesByExample(wishcodeExample);
								wishCodeResponse.setCode("1");
								wishCodeResponse.setWishcodes(list);
							}else {
								wishCodeResponse.setCode("3");
								wishCodeResponse.setDes("数据格式错误");
							}
						} else {
							
							wishCodeResponse.setCode("2");
							wishCodeResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						wishCodeResponse.setCode("2");
						wishCodeResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					wishCodeResponse.setCode("2");
					wishCodeResponse.setDes("请重新登录");
				}

			} else {
				// 未登录
				wishCodeResponse.setCode("2");
				wishCodeResponse.setDes("请重新登录");
			}
			logger.info("返回："
					+ mapper.writeValueAsString(wishCodeResponse));
		} catch (Exception e) {
			e.printStackTrace();
			wishCodeResponse.setCode("0");
			wishCodeResponse.setDes("系统繁忙请稍后再试！");
		}

		return wishCodeResponse;
	}
	//愿望支付
	@RequestMapping(value = "/buy", method = RequestMethod.POST)
	@ResponseBody
	public Object buyWish(HttpServletRequest request,
			@RequestBody BuyWishRequest buyWishRequest) {
		WishCodeResponse wishCodeResponse = new WishCodeResponse();
		try {
			logger.info("接收：" + mapper.writeValueAsString(buyWishRequest));
			String cookieId = request.getHeader("cookieId");
			if (cookieId != null) {
				CookieUser cookieUser = redisService.getObejct(cookieId,
						CookieUser.class);

				if (cookieUser != null) {
					String phoneNum = cookieUser.getPhoneNumber();
					if (phoneNum != null) {
						User user = userService.getUserByPhoneNumber(phoneNum);
						if (user != null) {
							int money = buyWishRequest.getMoney();
							String payType = buyWishRequest.getPayType();
							String wishId = buyWishRequest.getWishId();
							int wishCount = buyWishRequest.getWishCount();
							Double balance = user.getBalance();
							//Double vipBalance = user.getVipBalance();
							if(payType!=null&&!payType.equals("")&&wishId!=null&&!wishId.equals("")&&money>0&&wishCount>0){
									Wish wish = wishService.getWishById(wishId);
									if(wish!=null){
										Integer totalPrice = wish.getTotalPrice();
										Integer buyCount = wishbuyService.getSumBuyCount(wishId);
										if(buyCount!=null&&totalPrice!=null){
											int remain=totalPrice-buyCount;
											if(remain<=0){
												wishCodeResponse.setCode("4");
												wishCodeResponse.setDes("此愿望已结束");
												return wishCodeResponse;
											}else {
												int a=remain-wishCount;
												if(a<0){
													wishCodeResponse.setCode("4");
													wishCodeResponse.setDes("许愿次数已剩"+remain+"请重新选择许愿次数");
													return wishCodeResponse;
												}
											}
										}
										Wishbuy wishbuy = new Wishbuy();
										String uuid = UUIDGenerator.getUUID();
										wishbuy.setId(uuid);
										wishbuy.setBuyCount(wishCount);
										
										wishbuy.setCreateDate(new Date());
										wishbuy.setMoney(money);
										wishbuy.setUserId(phoneNum);
										wishbuy.setWishId(wishId);
										if(payType.equals("balance")){
											if(balance>=money){
												User user2 = new User();
												user2.setPhoneNumber(phoneNum);
												user2.setBalance(balance-money);
												wishbuy.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
												wishbuy.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
												wishbuyService.updateUserAndAddWishBuy(user2, wishbuy);
												wishCodeResponse.setCode("1");
												wishCodeResponse.setUuid(uuid);
												wishCodeResponse.setDes("许愿成功");
											}else {
												//余额不足
												wishCodeResponse.setCode("4");
												wishCodeResponse.setDes("余额不足");
											}
											
											
										}else if(payType.equals("personal")){
											wishCodeResponse.setCode("3");
											wishCodeResponse.setDes("请更新版本");
										/*	if(vipBalance>=money){
												User user2 = new User();
												user2.setPhoneNumber(phoneNum);
												user2.setVipBalance(vipBalance-money);
												wishbuy.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
												wishbuy.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
												wishbuyService.updateUserAndAddWishBuy(user2, wishbuy);
												wishCodeResponse.setCode("1");
												wishCodeResponse.setUuid(uuid);
												wishCodeResponse.setDes("许愿成功");
											}else {
												//余额不足
												wishCodeResponse.setCode("4");
												wishCodeResponse.setDes("个人会员卡余额不足");
											}*/
										}else if(payType.equals("VipBalance")){
											wishCodeResponse.setCode("3");
											wishCodeResponse.setDes("此功能只支持最新版本");
											
										}else if(payType.equals("business")){
											wishCodeResponse.setCode("3");
											wishCodeResponse.setDes("请更新版本");
											/*
											Integer companyRole = user.getCompanyRole();
											if(companyRole!=0){
												int i = payVipBanlanceService.updateUserAndAddWishBuy(user, wishbuy);
												if(i==1||i==2){
													wishCodeResponse.setCode("1");
													wishCodeResponse.setUuid(uuid);
													wishCodeResponse.setDes("许愿成功");
													return wishCodeResponse;
													
												}else if(i==3){
													//数据错误
													wishCodeResponse.setCode("3");
													wishCodeResponse.setDes("数据格式错误");
													return wishCodeResponse;
												}else if(i==4){
													//余额不足
													wishCodeResponse.setCode("4");
													wishCodeResponse
															.setDes("会员卡余额不足");
													return wishCodeResponse;
												}else if(i==0){
													//系统繁忙
													wishCodeResponse.setCode("0");
													wishCodeResponse.setDes("系统繁忙");
													return wishCodeResponse;
												}
											}else {
												wishCodeResponse.setCode("3");
												wishCodeResponse.setDes("您不是企业用户，不能使用企业会员卡支付");
												return wishCodeResponse;
											}
											
										*/}else if(payType.equals("weixin")){
											wishbuy.setStatus(PayCommonUtil.PAYPENDING_STATUS);
											wishbuy.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
											wishbuyService.addWishbuy(wishbuy);
											Date date = new Date();
											WxAppResponse wxAppResponse = new WxAppResponse();
											WxAppPayReq wxAppPayReq = new WxAppPayReq();
											wxAppPayReq.setPhone(phoneNum);
											wxAppPayReq.setUnitPrice((double)money);
											wxAppPayReq.setProductName("许愿");
											wxAppPayReq.setProductType(Const.WISH);
											wxAppPayReq.setProductId(uuid);
											WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
													.appPay(wxAppPayReq, request);
											BeanUtils.copyProperties(
													wxAppResponse, appPay);
											wxAppResponse.setCredateDate(date);
											wxAppResponse.setUuid(uuid);
											return wxAppResponse;
										}else {
											//支付方式错误
											wishCodeResponse.setCode("3");
											wishCodeResponse.setDes("支付方式错误");
										}
									}else {
										wishCodeResponse.setCode("3");
										wishCodeResponse.setDes("数据格式错误");
									}
							}else {
								//
								wishCodeResponse.setCode("3");
								wishCodeResponse.setDes("数据格式错误");
							}
						} else {
							
							wishCodeResponse.setCode("2");
							wishCodeResponse.setDes("请重新登录");
						}

					} else {
						// 未登录 登陆时间过期
						wishCodeResponse.setCode("2");
						wishCodeResponse.setDes("请重新登录");
					}
				} else {
					// 未登录
					wishCodeResponse.setCode("2");
					wishCodeResponse.setDes("请重新登录");
				}

			} else {
				// 未登录
				wishCodeResponse.setCode("2");
				wishCodeResponse.setDes("请重新登录");
			}
			logger.info("返回："
					+ mapper.writeValueAsString(wishCodeResponse));
		} catch (Exception e) {
			e.printStackTrace();
			wishCodeResponse.setCode("0");
			wishCodeResponse.setDes("系统繁忙请稍后再试！");
		}

		return wishCodeResponse;
	}	
	
		
	
}
